﻿using Furion.DatabaseAccessor.Extensions;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using iemtm.WeChat.Core;
using iemtm.WeChat.Core.Extension;
using iemtm.WeChat.Core.Managers;
using iemtm.WeChat.Core.Model;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace iemtm.WeChat.Application.SystemCenter
{
    public class InfoAppService : IInfoAppService, IDynamicApiController, ITransient
    {
        private readonly IWorkManager _workManager;
        private readonly IInfoManager _infoManager;


        public InfoAppService(IWorkManager workManager
            , IInfoManager infoManager
            )
        {
            _workManager = workManager;
            _infoManager = infoManager;
        }

        /// <summary>
        /// 加载所属公司
        /// </summary>
        /// <returns></returns>
        public dynamic GetCompanys()
        {
            var LoginInfo = _workManager.CurrentUser;
            return _infoManager.GetCompanys(LoginInfo);
        }
        /// <summary>
        /// 获取登录人信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public UserAccount GetUser()
        {
            return _workManager.CurrentUser;
        }
        [HttpGet]
        [QueryParameters]
        public  async Task<dynamic> GetAreas()
        {
            var LoginInfo = _workManager.CurrentUser;
            if (LoginInfo != null)
            {
                var AllAreas =await ($" WITH Areas AS( SELECT * FROM dbo.Area WHERE AreaCode='{LoginInfo.AreaCode}' AND	PrjCode='{LoginInfo.PrjCode}' UNION ALL SELECT b.* FROM Areas a INNER	JOIN dbo.Area b ON a.AreaCode=b.ParentCode)SELECT * FROM Areas").SqlQueryAsync();
                DataView dv = new DataView(AllAreas);
                //return dv.ToTable(true, "AreaCode", "ParentCode", "AreaName", "Administrativelevel", "PrjCode").ToJson();
                return AllAreas.ToJson();
            }
            return (new ResultModel() { Code = 0, Result = "会话过期" });
        }

        /// <summary>
        /// 获取用户
        /// </summary>
        /// <param name="UserName"></param>
        /// <returns></returns>
        [HttpGet]
        [QueryParameters]
        public async  Task<dynamic> GetPerson(string UserName = "")
        {
            var LoginInfo = _workManager.CurrentUser;
            if (LoginInfo != null)
            {
                List<UserAccount> persons = new List<UserAccount>();
                if (string.IsNullOrEmpty(UserName))
                {
                     persons = await _infoManager.GetUserAccountListAsync(u => u.CompanyCode.StartsWith(LoginInfo.CompanyCode));
                }
                else
                {
                     persons = await _infoManager.GetUserAccountListAsync(u => u.CompanyCode.StartsWith(LoginInfo.CompanyCode) && u.UserName.Contains(UserName));
                }
                return new ResultModel() { Code = 1, Result = persons };
            }
            return new ResultModel() { Code = 0, Result = "会话过期" };
        }
        

        #region  基站
        /// <summary>
        /// 基站列表
        /// </summary>
        /// <param name="AreaCode"></param>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">数目</param>
        /// <param name="pageStr"></param>
        /// <returns></returns>
        [HttpGet]
        [QueryParameters]
        public async Task<dynamic> GetBaseStationList(string AreaCode = "", int pageIndex = 1, int pageSize = 50, string pageStr = "")
        {
            var LoginInfo = _workManager.CurrentUser;
            if (LoginInfo != null)
            {
                if (string.IsNullOrEmpty(AreaCode))
                {
                    AreaCode = LoginInfo.AreaCode;
                }
                List<BaseStation> bs = new List<BaseStation>();
                if (string.IsNullOrEmpty(pageStr))
                {
                     bs = await _infoManager.GetBaseStationListAsync(b => b.PrjCode == LoginInfo.PrjCode  && b.AreaCode.StartsWith(AreaCode), pageIndex, pageSize);
                }
                else
                {
                     bs = await _infoManager.GetBaseStationListAsync(b => b.PrjCode == LoginInfo.PrjCode && b.BaseStationName.Contains(pageStr) && b.AreaCode.StartsWith(AreaCode), pageIndex, pageSize);
                }


               return new ResultModel() { Code = 1, Result = bs };
            }
            return (new ResultModel() { Code = 0, Result = "会话过期" });
        }

        [HttpGet]
        [QueryParameters]
        public async Task<dynamic> GetBaseStationById(string BaseStationCode)
        {
            BaseStation bs =await _infoManager.GetBaseStationFirstAsync(b => b.BaseStationCode == BaseStationCode);
            if (bs != null)
            {
                return (new ResultModel() { Code = 1, Result = bs });
            }
            return (new ResultModel() { Code = 0, Result = "会话过期" });
        }
        #endregion

        #region 告警
        /// <summary>
        /// 获取告警列表信息数量
        /// </summary>
        /// <param name="menuIndex"></param>
        /// <param name="cAreaName"></param>
        /// <param name="BaseStationName"></param>
        /// <param name="search"></param>
        /// <returns></returns>
        [HttpGet]
        [QueryParameters]
        public async Task<dynamic> GetAlarmListCount(int menuIndex, string cAreaName, string BaseStationName, int search)
        {
            var LoginInfo = _workManager.CurrentUser;
            string strwhereByAlarm = "";
            string strwhereByNum = "";
            if (search == 1)//是否选择点击按钮
            {
                strwhereByAlarm = (BaseStationName == "") ? ($" AND A.AreaCode LIKE '{cAreaName}%'") : ($" AND A.AreaCode LIKE '{cAreaName}%' AND A.BaseStationName LIKE '%{BaseStationName}%'");
                strwhereByNum = $" AND AreaCode LIKE '{cAreaName}%'";
            }
            if (LoginInfo != null)
            {
                switch (menuIndex)
                {
                    case 0://退服
                        var OutOfServiceCount = ( await ($"	select A.JobNumber,A.AreaCode,AreaName,SUBSTRING(A.AlarmOccTime,6,11) as AlarmOccTime,A.BaseStationCode,A.BaseStationName,B.BaseStationLevel ,A.Operators FROM  AlarmList A inner join BaseStation B on A.BaseStationCode = B.BaseStationCode where A.AreaCode in (select AreaCode from Area where ParentCode like('{LoginInfo.AreaCode}%') or AreaCode like ('{LoginInfo.AreaCode}%'))   AND	A.AlarmType='退服' {strwhereByAlarm} ORDER by A.AlarmOccTime desc").SqlQueryAsync()).Rows.Count;
                        return OutOfServiceCount;
                    case 1://停电
                        var PowerCutCount = (await ($" 	select A.JobNumber,A.AreaCode,AreaName,SUBSTRING(A.AlarmOccTime,6,11) as AlarmOccTime,A.BaseStationCode,A.BaseStationName,B.BaseStationLevel ,A.Operators FROM  AlarmList A inner join BaseStation B on A.BaseStationCode = B.BaseStationCode where A.AreaCode in (select AreaCode from Area where ParentCode like('{LoginInfo.AreaCode}%') or AreaCode like ('{LoginInfo.AreaCode}%'))   AND	A.AlarmType='停电' {strwhereByAlarm} ORDER by A.AlarmOccTime desc").SqlQueryAsync()).Rows.Count;
                        return PowerCutCount;
                    case 2://FSU离线
                        var FSUCount = (await ($" 	select A.JobNumber,A.AreaCode,AreaName,SUBSTRING(A.AlarmOccTime,6,11) as AlarmOccTime,A.BaseStationCode,A.BaseStationName,B.BaseStationLevel ,A.Operators FROM  AlarmList A inner join BaseStation B on A.BaseStationCode = B.BaseStationCode where A.AreaCode in (select AreaCode from Area where ParentCode like('{LoginInfo.AreaCode}%') or AreaCode like ('{LoginInfo.AreaCode}%'))   AND	A.AlarmType='FSU离线' {strwhereByAlarm} ORDER by A.AlarmOccTime desc").SqlQueryAsync()).Rows.Count;
                        return FSUCount;
                    case 3://低压
                        var LowTensionCount = (await ($"  select A.JobNumber,A.AreaCode,AreaName,SUBSTRING(A.AlarmOccTime,6,11) as AlarmOccTime,A.BaseStationCode,A.BaseStationName,B.BaseStationLevel ,A.Operators FROM  AlarmList A inner join BaseStation B on A.BaseStationCode = B.BaseStationCode where A.AreaCode in (select AreaCode from Area where ParentCode like('{LoginInfo.AreaCode}%') or AreaCode like ('{LoginInfo.AreaCode}%'))   AND	A.IsLowVoltage=1 {strwhereByAlarm} ORDER by A.AlarmOccTime desc").SqlQueryAsync()).Rows.Count;
                        return LowTensionCount;
                  
                    case 7://退服移动
                        var OutOfServiceByYDCount = (await ($"	select A.JobNumber,A.AreaCode,AreaName,SUBSTRING(A.AlarmOccTime,6,11) as AlarmOccTime,A.BaseStationCode,A.BaseStationName,B.BaseStationLevel ,A.Operators FROM  AlarmList A inner join BaseStation B on A.BaseStationCode = B.BaseStationCode where A.AreaCode in (select AreaCode from Area where ParentCode like('{LoginInfo.AreaCode}%') or AreaCode like ('{LoginInfo.AreaCode}%'))   AND	A.AlarmType='退服' AND	A.Operators LIKE '%移动%' ORDER by A.AlarmOccTime desc").SqlQueryAsync()).Rows.Count;
                        return OutOfServiceByYDCount;
                    case 8://退服联通
                        var OutOfServiceByLTCount = (await ($"	select A.JobNumber,A.AreaCode,AreaName,SUBSTRING(A.AlarmOccTime,6,11) as AlarmOccTime,A.BaseStationCode,A.BaseStationName,B.BaseStationLevel ,A.Operators FROM  AlarmList A inner join BaseStation B on A.BaseStationCode = B.BaseStationCode where A.AreaCode in (select AreaCode from Area where ParentCode like('{LoginInfo.AreaCode}%') or AreaCode like ('{LoginInfo.AreaCode}%'))   AND	A.AlarmType='退服' AND	A.Operators LIKE '%联通%' ORDER by A.AlarmOccTime desc").SqlQueryAsync()).Rows.Count;
                        return OutOfServiceByLTCount;
                    case 9://退服电信
                        var OutOfServiceByDXCount = (await ($"	select A.JobNumber,A.AreaCode,AreaName,SUBSTRING(A.AlarmOccTime,6,11) as AlarmOccTime,A.BaseStationCode,A.BaseStationName,B.BaseStationLevel ,A.Operators FROM  AlarmList A inner join BaseStation B on A.BaseStationCode = B.BaseStationCode where A.AreaCode in (select AreaCode from Area where ParentCode like('{LoginInfo.AreaCode}%') or AreaCode like ('{LoginInfo.AreaCode}%'))   AND	A.AlarmType='退服' AND	A.Operators LIKE '%电信%' ORDER by A.AlarmOccTime desc").SqlQueryAsync()).Rows.Count;
                        return OutOfServiceByDXCount;
                    case 10://停电移动
                        var PowerCutByYDCount = (await ($" 	select A.JobNumber,A.AreaCode,AreaName,SUBSTRING(A.AlarmOccTime,6,11) as AlarmOccTime,A.BaseStationCode,A.BaseStationName,B.BaseStationLevel ,A.Operators FROM  AlarmList A inner join BaseStation B on A.BaseStationCode = B.BaseStationCode where A.AreaCode in (select AreaCode from Area where ParentCode like('{LoginInfo.AreaCode}%') or AreaCode like ('{LoginInfo.AreaCode}%'))   AND	A.AlarmType='停电' AND	A.Operators LIKE '%移动%' ORDER by A.AlarmOccTime desc").SqlQueryAsync()).Rows.Count;
                        return PowerCutByYDCount;
                    case 11://停电联通
                        var PowerCutByLTCount = (await ($" 	select A.JobNumber,A.AreaCode,AreaName,SUBSTRING(A.AlarmOccTime,6,11) as AlarmOccTime,A.BaseStationCode,A.BaseStationName,B.BaseStationLevel ,A.Operators FROM  AlarmList A inner join BaseStation B on A.BaseStationCode = B.BaseStationCode where A.AreaCode in (select AreaCode from Area where ParentCode like('{LoginInfo.AreaCode}%') or AreaCode like ('{LoginInfo.AreaCode}%'))   AND	A.AlarmType='停电' AND	A.Operators LIKE '%联通%' ORDER by A.AlarmOccTime desc").SqlQueryAsync()).Rows.Count;
                        return PowerCutByLTCount;
                    case 12://停电电信
                        var PowerCutByDXCount = (await ($" 	select A.JobNumber,A.AreaCode,AreaName,SUBSTRING(A.AlarmOccTime,6,11) as AlarmOccTime,A.BaseStationCode,A.BaseStationName,B.BaseStationLevel ,A.Operators FROM  AlarmList A inner join BaseStation B on A.BaseStationCode = B.BaseStationCode where A.AreaCode in (select AreaCode from Area where ParentCode like('{LoginInfo.AreaCode}%') or AreaCode like ('{LoginInfo.AreaCode}%'))   AND	A.AlarmType='停电' AND	A.Operators LIKE '%电信%' ORDER by A.AlarmOccTime desc").SqlQueryAsync()).Rows.Count;
                        return PowerCutByDXCount;
                    default:
                        break;
                }
            }
            return (new ResultModel() { Code = 0, Result = "会话过期" });
        }

        /// <summary>
        /// 获取告警列表信息
        /// </summary>
        /// <param name="menuIndex"></param>
        ///  /// <param name="cAreaName"></param>
        /// <param name="BaseStationName"></param>
        /// <param name="search"></param>
        /// <returns></returns>
        [HttpGet]
        [QueryParameters]
        public async Task<dynamic> GetAlarmList(int menuIndex, string cAreaName, string BaseStationName, int search)
        {
            var LoginInfo = _workManager.CurrentUser;
            string strwhereByAlarm = "";
            string strwhereByNum = "";
            if (string.IsNullOrEmpty(cAreaName) && LoginInfo != null)
                cAreaName = LoginInfo.AreaCode;
            if (search == 1)//是否选择点击按钮
            {
                strwhereByAlarm = (BaseStationName == "") ? ($" AND A.AreaCode LIKE '{cAreaName}%'") : ($" AND A.AreaCode LIKE '{cAreaName}%' AND A.BaseStationName LIKE '%{BaseStationName}%'");
                strwhereByNum = $" AND AreaCode LIKE '{cAreaName}%'";
            }
            if (LoginInfo != null)
            {
                switch (menuIndex)
                {
                    case 0://退服
                        var OutOfService = await ($"	select A.JobNumber,A.AreaCode,AreaName,SUBSTRING(A.AlarmOccTime,6,11) as AlarmOccTime,A.BaseStationCode,A.BaseStationName,B.BaseStationLevel ,A.Operators FROM  AlarmList A inner join BaseStation B on A.BaseStationCode = B.BaseStationCode where A.AreaCode in (select AreaCode from Area where ParentCode like('{LoginInfo.AreaCode}%') or AreaCode like ('{LoginInfo.AreaCode}%'))   AND	A.AlarmType='退服' {strwhereByAlarm} ORDER by A.AlarmOccTime desc").SqlQueryAsync();
                        return OutOfService.ToJson();
                    case 1://停电
                        var PowerCut = await  ($" 	select A.JobNumber,A.AreaCode,AreaName,SUBSTRING(A.AlarmOccTime,6,11) as AlarmOccTime,A.BaseStationCode,A.BaseStationName,B.BaseStationLevel ,A.Operators FROM  AlarmList A inner join BaseStation B on A.BaseStationCode = B.BaseStationCode where A.AreaCode in (select AreaCode from Area where ParentCode like('{LoginInfo.AreaCode}%') or AreaCode like ('{LoginInfo.AreaCode}%'))   AND	A.AlarmType='停电' {strwhereByAlarm} ORDER by A.AlarmOccTime desc").SqlQueryAsync();
                        return PowerCut.ToJson();
                    case 2://FSU离线
                        var FSU = await ($" 	select A.JobNumber,A.AreaCode,AreaName,SUBSTRING(A.AlarmOccTime,6,11) as AlarmOccTime,A.BaseStationCode,A.BaseStationName,B.BaseStationLevel ,A.Operators FROM  AlarmList A inner join BaseStation B on A.BaseStationCode = B.BaseStationCode where A.AreaCode in (select AreaCode from Area where ParentCode like('{LoginInfo.AreaCode}%') or AreaCode like ('{LoginInfo.AreaCode}%'))   AND	A.AlarmType='FSU离线' {strwhereByAlarm} ORDER by A.AlarmOccTime desc").SqlQueryAsync();
                        return FSU.ToJson();
                    case 3://低压
                        var LowTension = await  ($"  select A.JobNumber,A.AreaCode,AreaName,SUBSTRING(A.AlarmOccTime,6,11) as AlarmOccTime,A.BaseStationCode,A.BaseStationName,B.BaseStationLevel ,A.Operators FROM  AlarmList A inner join BaseStation B on A.BaseStationCode = B.BaseStationCode where A.AreaCode in (select AreaCode from Area where ParentCode like('{LoginInfo.AreaCode}%') or AreaCode like ('{LoginInfo.AreaCode}%'))   AND	A.IsLowVoltage=1 {strwhereByAlarm} ORDER by A.AlarmOccTime desc").SqlQueryAsync();
                        return LowTension.ToJson();
                
                    default:
                        break;
                }
            }
            return new ResultModel() { Code = 0, Result = "会话过期" };
        }
        #endregion

        #region  发电记录
        /// <summary>
        /// 发电记录
        /// </summary>
        /// <param name="userCode"></param>
        /// <param name="prjCode"></param>
        /// <param name="openId"></param>
        /// <param name="type"></param>
        /// <param name="paraStr"></param>
        /// <param name="pagesize"></param>
        /// <param name="topNum"></param>
        /// <returns></returns>
        [HttpGet]
        [QueryParameters]
        public async Task<dynamic> GetGenRecord(string userCode, string prjCode, string openId, int type = 0, string paraStr = "", int pagesize = 50, int topNum = 0)
        {
            var loginfo = _workManager.CurrentUser;
           // DataSet ds = new DataSet();
            var whereStr = "";
            if (type == 1)//今日
            {
                whereStr = " and GenStart>=(select CONVERT(varchar(30),GETDATE(),23)+' 00:00:00') and GenStart<=(select CONVERT(varchar(30),GETDATE(),23)+' 23:59:59')";
            }
            if (type == 7)
            {
                whereStr = " and GenStart>=(select dateadd(day,-7,(select CONVERT(varchar(30),GETDATE(),23)))) and GenStart<=(select CONVERT(varchar(30),GETDATE(),23)+' 23:59:59')";
            }
            else if (type == 15)
            {
                whereStr = " and GenStart>=(select dateadd(day,-15,(select CONVERT(varchar(30),GETDATE(),23)))) and GenStart<=(select CONVERT(varchar(30),GETDATE(),23)+' 23:59:59')";
            }
            else if (type == 30)//本月
            {
                whereStr = " and GenStart>=(select substring(CONVERT(varchar(30),GETDATE(),23),0,8)+'-01 00:00:00')";
            }
            string Topwhere = " and GenRecordId>" + topNum.ToString(); //分页
            bool commonFilterJustByArea = loginfo.PerUrls.Contains("/DataPermission/CommonFilterJustByArea");
            var filterStr = commonFilterJustByArea ? "AreaCode like '" + loginfo.AreaCode + "%'" : "(companycode like '" + loginfo.CompanyCode + "%' and AreaCode like '" + loginfo.AreaCode + "%')";
           var  ds=await ("select top " + pagesize + " A.GenRecordId,A.GensetNum,A.GenStart,A.GenStop,A.RunningPeriod,A.KWpower,A.GenFee,A.IsManual from GenRecord A where A.PrjCode like '" + loginfo.PrjCode + "%'  and " + filterStr + " and  A.GensetNum like '%" + paraStr + "%'" + whereStr + Topwhere + " order by A.GenRecordId asc").SqlQueryAsync();
            //统计数量
            DataTable Total = await (" select  count(GenRecordId) from GenRecord A where A.PrjCode like '" + loginfo.PrjCode + "%'  and " + filterStr + " and  A.GensetNum like '%" + paraStr + "%'" + whereStr + " ").SqlQueryAsync();
            var dataTotal = Total.Rows[0][0];
            return new
            {
                total = dataTotal,
                data = ds.ToDynamicList()
            };

          
        }
        /// <summary>
        /// 发电明细
        /// </summary>
        /// <param name="GenRecordId"></param>
        /// <returns></returns>
        [HttpGet]
        [QueryParameters]
        public async Task<dynamic> GetGenRecordById(int GenRecordId)
        {
            GenRecord genRecord =await _infoManager.GetGenRecordFirstAsync(g => g.GenRecordId == GenRecordId);
               
            if (genRecord != null)
            {
                return new ResultModel() { Code = 1, Result = genRecord };
            }
            return new ResultModel() { Code = 0, Result = "会话过期" };
        }

        #endregion

        #region 指标通报
        /// <summary>
        /// 重要通知信息列表
        /// </summary>
        /// <param name="times"></param>
        /// <param name="paraStr"></param>
        /// <returns></returns>
        [HttpGet]
        [QueryParameters]
        public async Task<dynamic> GetImportantList(int times = 0, string paraStr = "")
        {
            var LoginInfo = _workManager.CurrentUser;
            if (LoginInfo != null)
            {
                var sql = "SELECT WXEditorId,EditorTitle,CreateName,EditorTxt,CreateTime,UpdateTime,UserCode,UserName,Status FROM WXEditor WHERE Status=1";
                var whereStr = "";
                if (times == 0)//全部
                {
                    whereStr = $"AND EditorTitle LIKE '%{paraStr}%' ORDER BY CreateTime DESC";
                }
                else if (times == 7)//7天内
                {
                    whereStr = $"AND CreateTime >= (select dateadd(day,-7,(select CONVERT(varchar(30),GETDATE(),23)))) AND CreateTime <= (select CONVERT(varchar(30),GETDATE(),23)+' 23:59:59') AND EditorTitle LIKE '%{paraStr}%' ORDER BY CreateTime DESC";
                }
                else if (times == 15)//半个月
                {
                    whereStr = $"AND CreateTime >= (select dateadd(day,-15,(select CONVERT(varchar(30),GETDATE(),23)))) AND CreateTime <= (select CONVERT(varchar(30),GETDATE(),23)+' 23:59:59') AND EditorTitle LIKE '%{paraStr}%' ORDER BY CreateTime DESC";
                }
                else if (times == 30)//本月
                {
                    whereStr = $"AND CreateTime >= (select substring(CONVERT(varchar(30),GETDATE(),23),0,8)+'-01 00:00:00') AND EditorTitle LIKE '%{paraStr}%' ORDER BY CreateTime DESC";
                }
                sql += whereStr;//组成sql语句
                try
                {
                    var dt = await (sql).SqlQueryAsync();
                    return new ResultModel() { Code = 1, Result = dt.ToJson() };
                }
                catch (Exception e)
                {
                    return new ResultModel() { Code = 0, Result = e.Message.ToString() };
                }
            }
            return new ResultModel() { Code = 0, Result = "会话过期" };
        }

        /// <summary>
        /// 根据登录区域获取工单数量
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [QueryParameters]
        public async Task<dynamic> GetAnnouceCountByArea(string date, int type = 0)
        {
            var LoginInfo = _workManager.CurrentUser;
            string startTime = DateTime.Now.ToString("yyyy/MM/dd") + " 00:00:00";
            string stopTime = DateTime.Now.ToString("yyyy/MM/dd") + " 23:59:59";
            //筛选日期处理 type=0:日报；1:周报；2:月报
            switch (type)
            {
                case 0://日报时间处理
                    if (string.IsNullOrEmpty(date))//页面初始化，不传值 默认当天
                        date = DateTime.Now.ToString();
                    startTime = Convert.ToDateTime(date).ToString("yyyy/MM/dd") + " 00:00:00";
                    stopTime = Convert.ToDateTime(date).ToString("yyyy/MM/dd") + " 23:59:59";
                    break;
                case 1://周报时间处理 
                    if (string.IsNullOrEmpty(date))
                        date = DateTime.Now.ToString();
                    startTime = GetWeekFirstDayMon(Convert.ToDateTime(date)).ToString("yyyy/MM/dd") + " 00:00:00";
                    stopTime = GetWeekLastDaySun(Convert.ToDateTime(date)).ToString("yyyy/MM/dd") + " 23:59:59";
                    break;
                case 2://月报时间处理 传过来为XXXX年XX月XX日 日为当月最后一天
                    if (string.IsNullOrEmpty(date))//页面初始化，不传值 默认当天
                        date = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(1).AddDays(-1).ToString("yyyy/MM/dd");
                    startTime = Convert.ToDateTime(date).ToString("yyyy/MM") + "/01 00:00:00";
                    stopTime = Convert.ToDateTime(date).ToString("yyyy/MM/dd") + " 23:59:59";
                    break;
                default:
                    break;
            }
            if (LoginInfo != null)
            {
                //获取所有的子区域和自己区域
                var sqlAreaName = $"SELECT a.AreaCode,a.AreaName,a.ParentCode,a.Administrativelevel,b.AreaName as ParentName FROM dbo.Area a left join area b on a.parentcode=b.areacode WHERE  a.ParentCode='{LoginInfo.AreaCode}' OR a.AreaCode='{LoginInfo.AreaCode}' order by a.Administrativelevel";
                var sqlAllAnnouceCount = "";//总共单sql
                var sqlFiAnnnouceCount = "";//已完成工单sql
                var sqlnoExtAnnouceCount = "";//未接单sql

                var AreaList =await (sqlAreaName).SqlQueryAsync();
                if (AreaList == null)
                    return (new ResultModel() { Code = 0, Result = "会话过期 -AreaList=null" });

                List<AnnouceCountByAreaModel> AnnouceCount = new List<AnnouceCountByAreaModel>();

                foreach (DataRow dr in AreaList.Rows)
                {
                    AnnouceCountByAreaModel a = new AnnouceCountByAreaModel();
                    //先把统计报表AreaName字段赋值
                    a.AreaName = dr["AreaName"].ToString();

                    //赋值字段AllAnnouceCount总工单数
                    sqlAllAnnouceCount = $"SELECT COUNT(AnnounceId) AS Count FROM dbo.AnnounceList WHERE AreaCode LIKE '{dr["AreaCode"].ToString()}%' AND CreateDate BETWEEN '{startTime}' AND '{stopTime}'";
                    DataTable AllAnnouceCountDt = await  (sqlAllAnnouceCount).SqlQueryAsync();
                    if (AllAnnouceCountDt == null)
                        a.AllAnnouceCount = 0;
                    else
                        a.AllAnnouceCount = Convert.ToInt32(AllAnnouceCountDt.Rows[0]["Count"]);

                    //赋值字段FiAnnnouceCount已完成工单数
                    sqlFiAnnnouceCount = $"SELECT AnnounceCode FROM dbo.AnnounceGen WHERE AnnounceCode IN (SELECT AnnounceCode FROM dbo.AnnounceList WHERE AreaCode LIKE '{dr["AreaCode"].ToString()}%' AND CreateDate BETWEEN '{startTime}' AND '{stopTime}' ) GROUP BY AnnounceCode";
                    DataTable FiAnnnouceCountDt = await  (sqlFiAnnnouceCount).SqlQueryAsync();
                    if (FiAnnnouceCountDt == null)
                        a.FiAnnnouceCount = 0;
                    else
                        a.FiAnnnouceCount = FiAnnnouceCountDt.Rows.Count;

                    //赋值字段noExtAnnouceCount未接工单数
                    sqlnoExtAnnouceCount = $"SELECT COUNT(AnnounceId) AS Count FROM dbo.AnnounceList WHERE AreaCode LIKE '{dr["AreaCode"].ToString()}%' AND	 AnnounceStatus=20 AND CreateDate BETWEEN '{startTime}' AND '{stopTime}'";
                    DataTable noExtAnnouceCountDt = await (sqlnoExtAnnouceCount).SqlQueryAsync();
                    if (noExtAnnouceCountDt == null)
                        a.noExtAnnouceCount = 0;
                    else
                        a.noExtAnnouceCount = Convert.ToInt32(noExtAnnouceCountDt.Rows[0]["Count"]);
                    AnnouceCount.Add(a);
                }
                return new ResultModel() { Code = 1, Result = AnnouceCount };
            }
            return new ResultModel() { Code = 0, Result = "会话过期" };
        }






        /// <summary>  
        /// 得到本周第一天(以星期一为第一天)  
        /// </summary>  
        /// <param name="datetime"></param>  
        /// <returns></returns>  
        private DateTime GetWeekFirstDayMon(DateTime datetime)
        {
            //星期一为第一天  
            int weeknow = Convert.ToInt32(datetime.DayOfWeek);

            //因为是以星期一为第一天，所以要判断weeknow等于0时，要向前推6天。  
            weeknow = (weeknow == 0 ? (7 - 1) : (weeknow - 1));
            int daydiff = (-1) * weeknow;

            //本周第一天  
            string FirstDay = datetime.AddDays(daydiff).ToString("yyyy-MM-dd");
            return Convert.ToDateTime(FirstDay);
        }

        /// <summary>  
        /// 得到本周最后一天(以星期天为最后一天)  
        /// </summary>  
        /// <param name="datetime"></param>  
        /// <returns></returns>  
        private DateTime GetWeekLastDaySun(DateTime datetime)
        {
            //星期天为最后一天  
            int weeknow = Convert.ToInt32(datetime.DayOfWeek);
            weeknow = (weeknow == 0 ? 7 : weeknow);
            int daydiff = (7 - weeknow);

            //本周最后一天  
            string LastDay = datetime.AddDays(daydiff).ToString("yyyy-MM-dd");
            return Convert.ToDateTime(LastDay);
        }
        #endregion
    }
}
